package com.ljc.controller;

import com.ljc.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("file")
@CrossOrigin
public class FileController {
    @Value("${file.path}")
    private String fileDir;

    @RequestMapping("upload")
    public Result upload(MultipartFile file) {
        Result result = new Result();
        String newFileName=file.getOriginalFilename();
        String suffix=newFileName.substring(newFileName.lastIndexOf("."));
        newFileName= UUID.randomUUID()+suffix;
        File saveFile=new File(fileDir, newFileName);
        try {
            file.transferTo(saveFile);
            result.setStatus(1).setMsg("上传成功").setData(newFileName);
        } catch (IOException e) {
            e.printStackTrace();
            result.setStatus(0).setMsg("上传失败");
        }
        return result;
    }
}